const app = getApp();
const serversFace = require('../utils/server.config.js');
const API = require('../utils/api.js');

const methods = {

   /**
    * 提交fromid
    */
   postFromId(formId) {
      if (!formId || formId == 'the formId is a mock one') {
         return;
      }
      var param = {
         formId: formId
      };
      API.postFromId(param, (success) => {
         console.log('提交fromid返回')
         console.log(success)
      }, () => {}, this);
   },

   /**
    * 打开小程序
    */
   miniProgram: function(appId, path) {
      let that = this;
      wx.navigateToMiniProgram({
         appId: appId,
         path: path,
         envVersion: 'release',
         success(res) {
            console.log('跳')
         },
         fail: function() {
            console.log('fail')
         }
      })
   },

   /**
    * 发起微信支付
    * @timeStamp  {int}->时间戳
    * @nonceStr  {String}->随机字符串
    * @package  {String}->统一下单接口返回的 prepay_id 参数值
    * @signType  {String}->签名算法，暂支持 MD5
    * @paySign  {String}->签名
    */
   launchWeixinPayMethod: function(res, callback) {
      let that = this;
      wx.requestPayment({
         timeStamp: res.timeStamp,
         nonceStr: res.nonceStr,
         package: res.package,
         signType: 'MD5',
         paySign: res.paySign,
         success: function(res) {
            console.log('支付成功')
            console.log(res)
            that.showToastGlobalTip('支付成功', 'success');
            callback(res);
         },
         fail: function(res) {
            console.log('支付失败')
            console.log(res)
            if (res.errMsg === 'requestPayment:fail cancel') {
               console.log('用户取消支付')
            } else {
               wx.hideLoading();
               if (wx.canIUse('showToast.image')) {
                  that.showToastGlobalTip('支付失败', 'none');
               } else {
                  that.showToastGlobalTip('支付失败', 'none');
               }
            }
         },
         complete: function(res) {
            wx.hideLoading();
         },
      })
   },



   /**
    * 全局模态框 提示方法
    * @titles  {String}->提示标题
    * @tiptext  {String}->提示文本内容
    * @iscancel  {Boolean}->是否显示取消按钮
    * @canceltext  {Boolean}->取消按钮文本
    * @confirmtext  {String}->确定按钮文本
    * showModal(titles, tiptext, iscancel, canceltext, confirmtext, callback);
    */
   showModal: function(titles, tiptext, iscancel, canceltext, confirmtext, callback) {
      wx.showModal({
         title: titles,
         content: tiptext,
         showCancel: iscancel,
         cancelText: canceltext,
         confirmText: confirmtext,
         confirmColor: "#555",
         success: function(res) {
            if (res.confirm) {
               callback(true);
            } else {
               callback(false);
            }
         }
      })
   },

   /**
    * 全局showToast消息提示框
    * @title：提示内容
    * @icon：提示icon
    */
   showToast: function(title, icon) {
      let that = this;
      wx.showToast({
         title: title,
         icon: icon,
         duration: 2000
      })
   },

   /**
    * 全局隐藏hideToast 消息提示框
    */
   hideToast: function() {
      setTimeout(function() {
         wx.hideToast();
      }, 500)
   },


   /**
    * 全局loading 提示框
    * @title：loading提示信息
    * @mask：是否显示透明蒙层，防止触摸穿透，默认：false
    */
   showLoading: function(title) {
      let that = this;
      wx.showLoading({
         title: title,
         mask: true,
      })
   },

   /**
    * 全局隐藏loading 提示框
    */
   hideLoading: function() {
      if (wx.hideLoading) {
         wx.hideLoading();
      } else {
         wx.hideLoading();
      }
   },

   /**
    * 时间戳转日期
    * @types  {String}->转换类型
    * @timestamp  {String}->时间戳
    */
   formatMsgTimeBlobal: function(types, timestamp) {
      // 补全为13位
      var arrTimestamp = (timestamp + '').split('');
      for (var start = 0; start < 13; start++) {
         if (!arrTimestamp[start]) {
            arrTimestamp[start] = '0';
         }
      }
      timestamp = arrTimestamp.join('') * 1;

      var minute = 1000 * 60;
      var hour = minute * 60;
      var day = hour * 24;
      var halfamonth = day * 15;
      var month = day * 30;
      var now = new Date().getTime();
      var diffValue = now - timestamp;
      var returnValue = 0,
         sfmValue = 0;
      // 计算差异时间的量级
      var monthC = diffValue / month;
      var weekC = diffValue / (7 * day);
      var dayC = diffValue / day;
      var hourC = diffValue / hour;
      var minC = diffValue / minute;


      /**转换格式二 YYMMDD */
      if (types == 'detas') {
         // 数值补0方法
         var zero = function(value) {
            if (value < 10) {
               returnValue = '0' + value;
               return returnValue;
            }
            return value;
         };
         return (function() {
            var date = new Date(timestamp);
            returnValue = date.getFullYear() + '.' + zero(date.getMonth() + 1) + '.' + zero(date.getDate());
            return returnValue;
         })();
      } else {
         //HHMMSS
         // 数值补0方法
         var zero = function(value) {
            if (value < 10) {
               sfmValue = '0' + value;
               return sfmValue;
            }
            return value;
         };
         return (function() {
            var date = new Date(timestamp);
            sfmValue = zero(date.getHours()) + ':' + zero(date.getMinutes()) + ':' + zero(date.getSeconds());
            return sfmValue;
         })();
      }
      return '刚刚';
   },

   /**
    * 时间戳转时分秒
    * @times:今天剩余多少秒
    */
   timeStampToHMS: function(times, callback) {
      var hours = Math.floor(times / 3600);
      var minutes = Math.floor(times % 3600 / 60);
      var seconds = Math.ceil(times % 60);
      // 数值补0方法
      var zero = function(value) {
         if (value < 10) {
            var returnValue = '0' + value;
            return returnValue;
         }
         return value;
      };
      var Times = zero(hours) + ":" + zero(minutes) + ":" + zero(seconds);

      callback(Times);
   },

   /**
    * @获取当前时间，年月日
    * @ttype {String} 返回格式类型
    */
   wxxGetThisTime(ttype) {
      let that = this;
      var date = new Date(),
         year = date.getFullYear(),
         month = date.getMonth(),
         day = date.getDate(),
         h = date.getHours(),
         m = date.getMinutes(),
         timeA = zero(year + '' + zero(month + 1) + '' + zero(day)), //YYMMDD
         timeB = zero(year + '.' + zero(month + 1) + '.' + zero(day)), //YY.MM.DD
         timeC = zero(year + '.' + zero(month + 1) + '.' + zero(day) + ' ' + zero(h) + ':' + zero(m)), //YY.MM.DD HH:MM
         timeD = zero(year + '/' + zero(month + 1) + '/' + zero(day) + ' ' + zero(h) + ':' + zero(m)), //YY/MM/DD HH:MM
         timeE = zero(year + '-' + zero(month + 1) + '-' + zero(day) + ' ' + zero(h) + ':' + zero(m)); //YY-MM-DD HH:MM
      // 数值补0方法
      function zero(value) {
         if (value < 10) {
            var returnValue = '0' + value;
            return returnValue;
         }
         return value;
      }

      if (ttype == 'a') {
         return timeA;
      } else if (ttype == 'b') {
         return timeB;
      } else if (ttype == 'c') {
         return timeC;
      } else if (ttype == 'd') {
         return timeD;
      } else if (ttype == 'e') {
         return timeE;
      }  else {
         return timeA;
      }
   },

   /**
    * 下载分享图，二维码
    * @downFill {Object} 需要下载的资源
    * @count {Int} 需要下载的资源数量
    * @callback {Function} 下载成功回调
    */
   downloadCanvasImgMatter(downFill, count, callback, failback) {
      let that = this,
         arr = [];
      wx.showLoading({
         title: '资源下载中',
         mask: true,
      })
      console.log(downFill)
      for (var key in downFill) {
         if (downFill[key]) {
            downFillMethod(downFill[key], key, (keys, file) => {
               downFill[keys] = file;
               arr.push(file)
               console.log('下载进度：', arr.length + "  ", file)
               if (arr.length >= count) {
                  callback(downFill);
                  wx.hideLoading();
               }
            });
         } else {
            downFill[key] = 'null';
            arr.push('null')
            if (arr.length >= count) {
               app.data.downFill = downFill;
               callback(downFill);
               wx.hideLoading();
            }
         }
      }

      function downFillMethod(url, key, callback) {
         wx.downloadFile({
            url: url,
            success(res) {
               callback(key, res.tempFilePath);
            },
            fail(res) {
               console.log('资源下载失败', res)
               callback(key, 'null');
               wx.showToast({
                  title: '资源下载失败，请稍后重试',
                  icon: 'none',
               })
            },
         })
      }

   },

};
module.exports = methods;